/**
 * 
 */
package com.pocketsweet.ui;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVMobilePhoneVerifyCallback;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.RequestMobileCodeCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * @author bobhu 注册页面
 */
@ContentView(R.layout.activity_indentification_mobile)
public class IndentifiedMobile extends BaseActivity {

	@ViewInject(R.id.etPhoneNumber)
	private EditText etPhoneNumber;

	@ViewInject(R.id.btn_sms_retry)
	private TextView btnSmsRetry;

	@ViewInject(R.id.etSmsCode)
	private EditText etSmsCode;

	@ViewInject(R.id.mainHeader)
	private HeaderLayout header;

	@ViewInject(R.id.btnClose)
	private ImageView btnClose;

	private String phone;
	private long mExitTime = 0;// 退出事件用到的事件

	private LoadingDailog mLoadingDialog;
	private Timer timer;
	private final int TIMERMSG = 0x01;
	private int time = 60;
	private boolean getted = false;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TIMERMSG:
				if (time != 0) {
					time--;
					btnSmsRetry.setText(time + "s后再次获取");
				} else if (time == 0) {
					timer.cancel();
					getted = false;
					btnSmsRetry.setText("获取验证码");
					time = 60;
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mLoadingDialog = ToolKits.createLoadingDialog(this, "验证中...");
		mLoadingDialog.setText("加载中");
		setHeaderFunction();
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("下一步");
		header.setMiddleText("绑定手机号");
		header.setRighttContainerClickListener(new onRightContainerListener() {
			@Override
			public void onClick() {
				if (StringUtils.isEmpty(etPhoneNumber.getText().toString())) {
					ToolKits.toast(IndentifiedMobile.this, "手机号不能为空");
					return;
				}
				if (!(etPhoneNumber.getText().toString().equals(phone))) {
					ToolKits.toast(IndentifiedMobile.this, "手机号与刚刚填写不一致");
					return;
				}
				String smsCode = etSmsCode.getText().toString();
				if (TextUtils.isEmpty(smsCode)) {
					ToolKits.toast(IndentifiedMobile.this,
							R.string.sms_code_empty);
					return;
				}
				mLoadingDialog.show();
				AVOSCloud.verifySMSCodeInBackground(smsCode, phone,
						new AVMobilePhoneVerifyCallback() {

							@Override
							public void done(AVException e) {
								mLoadingDialog.dismiss();
								if (e != null) {
									ToolKits.toast(IndentifiedMobile.this,
											e.getCode() + e.getMessage());
									return;
								}
								UserService.getCurrentUser().setNotifyPhone(
										phone);// 保存手机号码

								UserService.getCurrentUser().saveInBackground(
										new SaveCallback() {

											@Override
											public void done(AVException arg0) {
												// TODO Auto-generated method
												// stub
												if (arg0 == null) {
													// 验证通过进入下一个页面
													timer.cancel();
													ToolKits.toast(
															IndentifiedMobile.this,
															"绑定成功");

													Intent infoInent = new Intent(
															IndentifiedMobile.this,
															IdentificationMobileConfirm.class);
													IndentifiedMobile.this
															.startActivity(infoInent);
													IndentifiedMobile.this
															.finish();
												} else if (arg0.getCode() == 214) {
													ToolKits.toast(
															IndentifiedMobile.this,
															"绑定失败,此号码已被使用");
												} else {
													ToolKits.toast(
															IndentifiedMobile.this,
															"绑定失败");
												}
											}
										});

							}
						});
			}
		});
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				IndentifiedMobile.this.finish();
			}
		});
	}

	@OnClick(R.id.btn_sms_retry)
	public void onSmsRetryClick(View view) {
		phone = etPhoneNumber.getText().toString();
		if (StringUtils.isEmpty(phone)) {
			ToolKits.toast(IndentifiedMobile.this, "手机号不能为空");
			return;
		}
		if (getted == true) {
			return;
		}
		getted = true;
		// 如果你的账号需要重新发送短信请参考下面的代码
		AVOSCloud.requestSMSCodeInBackground(phone,
				new RequestMobileCodeCallback() {

					@Override
					public void done(AVException e) {
						if (e != null) {
							ToolKits.toast(IndentifiedMobile.this,
									"" + e.getCode());
							ToolKits.toast(IndentifiedMobile.this,
									e.getMessage());
							return;
						}
						ToolKits.toast(IndentifiedMobile.this,
								R.string.verify_sms_code_send);

					}
				});
		timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				Message message = new Message();
				message.what = TIMERMSG;
				handler.sendMessage(message);
			}
		}, 0, 1000);
	}

	/**
	 * 重写onKeyDown方法
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitAlet();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showExitAlet() {
		if ((System.currentTimeMillis() - mExitTime) > 2000) {
			Toast toast = Toast.makeText(IndentifiedMobile.this, "再按一次退出程序",
					Toast.LENGTH_LONG);
			// 可以控制toast显示的位置
			toast.setGravity(Gravity.BOTTOM, 0, 150);
			toast.show();
			mExitTime = System.currentTimeMillis();

		} else {
			IndentifiedMobile.this.finish();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
